package com.xpstem.lelink.connection;

import com.xpstem.lelink.command.EV3ReplyCallback;
import com.xpstem.lelink.command.EV3ReplyPackage;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Reply {

    private int counter;
    private EV3ReplyCallback callback;
    private byte[] data;
    private CountDownLatch downLatch;

    public Reply(int counter, EV3ReplyCallback callback) {
        this.counter = counter;
        this.callback = callback;
    }

    public void await(int timeout) throws InterruptedException {
        downLatch = new CountDownLatch(1);
        downLatch.await(timeout, TimeUnit.SECONDS);
    }

    public void response(byte[] data) {
        this.data = data;
        if (downLatch != null) {
            // 同步响应
            downLatch.countDown();
        }
        if (callback != null) {
            // 异步响应
            EV3ReplyPackage replyPackage = new EV3ReplyPackage(counter, data);
            callback.call(replyPackage);
        }
    }

    public int getCounter() {
        return counter;
    }

    public byte[] getData() {
        return data;
    }
}
